

package com.zdkj.subway.rca.controller;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.dto.CkMarketingTicketElecConfirmDTO;
import com.zdkj.subway.rca.dto.SwCkElectronicReceiptConfirmDTO;
import com.zdkj.subway.rca.entity.SwCkElectronicReceipt;
import com.zdkj.subway.rca.entity.SwCkElectronicReceiptExport;
import com.zdkj.subway.rca.enums.DEL_FLAG;
import com.zdkj.subway.rca.service.SwCkElectronicReceiptService;
import com.zdkj.subway.rca.service.SwCkMarketingTicketElecService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.util.Optional;


/**
 * 电子回执单
 *
 * @author cooze
 * @date 2020-10-24 21:52:04
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swckelectronicreceipt")
@Api(value = "swckelectronicreceipt", tags = "银行票据单管理-电子回执单管理")
@Slf4j
public class SwCkElectronicReceiptController extends SwCkElectronicReceiptBaseController {

    private final SwCkElectronicReceiptService swCkElectronicReceiptService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SwCkMarketingTicketElecService swCkMarketingTicketElecService;


    @ApiOperation(value = "查询票种类", notes = "查询票种类")
    @GetMapping("/ticketType")
    public R ticketType() {
        return R.ok(swCkElectronicReceiptService.getAllTicketType());
    }

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "lineCode", value = "线路编码", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "stationCode", value = "车站编码", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "ticketType", value = "票种CODE", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "paymentType", value = "支付方式 10：现金支付 12：支付宝支付 13：微信支付 14：银行转账", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "confirmStatus", value = "对账状态 0：未完成 1：已完成", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "returnOrderType", value = "电子回执单类型 1：转账 2：团购 3：平台 ", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class)
            }
    )
    @GetMapping("/page")
    public R getSwCkElectronicReceiptPage(Page page,
                                          String lineCode,
                                          String stationCode,
                                          String ticketType,
                                          String paymentType,
                                          String returnOrderType,
                                          String confirmStatus,
                                          String startDate,
                                          String endDate) {
        Optional<R> r = validate(returnOrderType);
        if (r.isPresent()) {
            return r.get();
        }

        SwCkElectronicReceipt swCkElectronicReceipt = new SwCkElectronicReceipt();
        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate);
        swCkElectronicReceipt.setReturnOrderType(returnOrderType);
        if (StringUtils.isNotEmpty(confirmStatus)) {
            swCkElectronicReceipt.setConfirmStatus(confirmStatus);
        }
        if (StringUtils.isNotEmpty(lineCode)) {
            swCkElectronicReceipt.setLineCode(lineCode);
        }
        if (StringUtils.isNotEmpty(stationCode)) {
            swCkElectronicReceipt.setStationCode(stationCode);
        }
        if (StringUtils.isNotEmpty(ticketType)) {
            swCkElectronicReceipt.setTicketType(ticketType);
        }
        if (StringUtils.isNotEmpty(paymentType)) {
            swCkElectronicReceipt.setPaymentType(paymentType);
        }
        swCkElectronicReceipt.setDelFlag(DEL_FLAG.NO.getCode());
        return R.ok(swCkElectronicReceiptService.page(page, Wrappers.query(swCkElectronicReceipt).lambda()
                .between(isDateCondition, SwCkElectronicReceipt::getBookkeepingTime, startDate, endDate)));
    }


    /**
     * 通过id查询电子账单
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swCkElectronicReceiptService.getById(id));
    }

    // TODO: 2020/10/25 先屏蔽不做
//    /**
//     * 新增电子账单
//     *
//     * @param swCkElectronicReceipt 电子账单
//     * @return R
//     */
//    @ApiOperation(value = "新增电子账单", notes = "新增电子账单")
//    @SysLog("新增电子账单")
//    @PostMapping
//    @PreAuthorize("@pms.hasPermission('rca_swckelectronicreceipt_add')")
//    public R save(@RequestBody SwCkElectronicReceipt swCkElectronicReceipt) {
//        return R.ok(swCkElectronicReceiptService.save(swCkElectronicReceipt));
//    }

    /**
     * 修改电子账单
     *
     * @param swCkElectronicReceipt 电子账单
     * @return R
     */
    @ApiOperation(value = "修改电子账单", notes = "修改电子账单")
    @SysLog("修改电子账单")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('rca_swckelectronicreceipt_edit')")
    public R updateById(@RequestBody SwCkElectronicReceipt swCkElectronicReceipt) {
        return R.ok(swCkElectronicReceiptService.updateById(swCkElectronicReceipt));
    }

    /**
     * 电子账单导出
     * @param export
     * @param response
     */
    @ApiOperation(value = "电子账单导出", notes = "电子账单导出")
    @PostMapping("/exportExcel")
    @PreAuthorize("@pms.hasPermission('rca_swckelectronicreceipt_export_excel')")
    public void exportExcel(@RequestBody SwCkElectronicReceiptExport export, HttpServletResponse response) {

        this.swCkElectronicReceiptService.exportExcel(export, response);
    }

    /**
     * 确认电子账单
     * @param dto
     * @return
     */
    @ApiOperation(value = "确认电子账单", notes = "确认电子账单")
    @PostMapping("/confirmStatus")
    @SysLog("确认电子账单")
    @PreAuthorize("@pms.hasPermission('rca_swckelectronicreceipt_confirm_status')")
    public R confirmStatus(@RequestBody SwCkElectronicReceiptConfirmDTO dto) {
        Optional<R> r = validate(dto.getReturnOrderType());
        if (r.isPresent()) {
            return r.get();
        }
        String md5 = MD5.create().digestHex(dto.toString());
        if (noPass(SecurityUtils.getUser().getId(), "confirmStatus", md5)) {
            return R.failed("请勿重复提交");
        }
        if (CollectionUtils.isEmpty(dto.getIdList())) {
            return R.failed("ID 列表不能为空");
        }
        this.swCkElectronicReceiptService.confirmStatus(dto);
        return R.ok();
    }

    /**
     * 营销车票与电子回执单数据对账查询
     * @param ticketType
     * @param confirmStatus
     * @param startDate
     * @param endDate
     * @return
     */
    @ApiOperation(value = "营销车票与电子回执单数据对账查询", notes = "营销车票与电子回执单数据对账查询")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "ticketType", value = "票种", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "confirmStatus", value = "对账状态 0：未完成 1：已完成", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class)
            }
    )
    /**
     * 查询营销车票
     * @param ticketType
     * @param confirmStatus
     * @param startDate
     * @param endDate
     * @return
     */
    @GetMapping("/queryMarketingTicket")
    public R queryCkMarketingTicketElec(String ticketType, String confirmStatus, String startDate, String endDate) {
        return R.ok(swCkElectronicReceiptService.queryCkMarketingTicketElec(ticketType, confirmStatus, startDate, endDate));
    }

    /**
     * 确认-营销车票与电子回执单
     * @param dto
     * @return
     */
    @ApiOperation(value = "确认-营销车票与电子回执单", notes = "(因为未确认数据没有ID，所以需要全量将数据提交上来)")
    @PostMapping("/ckMteConfirm")
    @SysLog("确认-营销车票与电子回执单")
    @PreAuthorize("@pms.hasPermission('rca_swckelectronicreceipt_ckmte_confirm')")
    public R ckMarketingTicketElecConfirm(@RequestBody CkMarketingTicketElecConfirmDTO dto) {
        if (CollectionUtils.isEmpty(dto.getMtEleList())) {
            return R.failed("请选择确认数据");
        }
        String md5 = MD5.create().digestHex(dto.toString());
        if (noPass(SecurityUtils.getUser().getId(), "ckMteConfirm", md5)) {
            return R.failed("请勿重复提交");
        }
        fixCkMarketingTicketElecConfirmData(dto);
        log.debug("request data={}", JSON.toJSON(dto));
        swCkMarketingTicketElecService.saveBatch(dto.getMtEleList());
        return R.ok();
    }

    /**
     * redis对象初始化
     */
    @Override
    public RedisTemplate<String, String> redisTemplate() {
        return redisTemplate;
    }
}
